<template>
  <view class="receipt-upload-container">
    <u-form :model="receiptForm" ref="receiptFormRef" :rules="rules" label-position="top">
      <u-form-item label="报销人" prop="userName">
        <u-input v-model="receiptForm.userName" placeholder="请输入报销人姓名" disabled />
      </u-form-item>
      
      <u-form-item label="部门" prop="department">
        <u-input v-model="receiptForm.department" placeholder="请输入部门" disabled />
      </u-form-item>
      
      <u-form-item label="招待日期" prop="date">
        <u-datetime-picker
          v-model="receiptForm.date"
          mode="date"
          :show-toolbar="true"
          @confirm="dateConfirm">
          <u-input
            v-model="receiptForm.dateDisplay"
            placeholder="请选择招待日期"
            disabled
            suffixIcon="calendar"
          />
        </u-datetime-picker>
      </u-form-item>
      
      <u-form-item label="招待事由" prop="reason">
        <u-textarea v-model="receiptForm.reason" placeholder="请输入招待事由" />
      </u-form-item>
      
      <u-form-item label="招待金额" prop="amount">
        <u-input
          v-model="receiptForm.amount"
          placeholder="请输入招待金额"
          type="number"
          suffix-icon="rmb-circle"
        />
      </u-form-item>
      
      <u-form-item label="支付凭证" prop="paymentReceipt">
        <u-upload
          :file-list="paymentReceiptList"
          @afterRead="afterPaymentReceiptRead"
          @delete="deletePaymentReceipt"
          :max-count="1"
          width="200"
          height="200"
        />
      </u-form-item>
      
      <u-form-item label="发票" prop="invoice">
        <u-upload
          :file-list="invoiceList"
          @afterRead="afterInvoiceRead"
          @delete="deleteInvoice"
          :max-count="1"
          width="200"
          height="200"
        />
      </u-form-item>
      
      <view class="form-actions">
        <u-button type="primary" @click="submitForm" :loading="loading">提交</u-button>
        <u-button @click="resetForm" :disabled="loading">重置</u-button>
      </view>
    </u-form>
  </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data() {
    return {
      loading: false,
      receiptForm: {
        userName: '',
        department: '',
        date: '',
        dateDisplay: '',
        reason: '',
        amount: '',
        paymentReceipt: null,
        invoice: null
      },
      rules: {
        date: [
          { required: true, message: '请选择招待日期', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入招待事由', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入招待金额', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
        ],
        paymentReceipt: [
          { required: true, message: '请上传支付凭证', trigger: 'change' }
        ],
        invoice: [
          { required: true, message: '请上传发票', trigger: 'change' }
        ]
      },
      paymentReceiptList: [],
      invoiceList: []
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  onLoad() {
    // 设置用户信息
    this.receiptForm.userName = this.userInfo.name || ''
    this.receiptForm.department = '财务部' // 模拟数据，实际应从用户信息获取
  },
  methods: {
    // 日期确认
    dateConfirm(e) {
      this.receiptForm.dateDisplay = this.$utils.formatDate(e.value, 'YYYY-MM-DD')
    },
    
    // 上传支付凭证
    afterPaymentReceiptRead(event) {
      const { file } = event
      
      // 检查文件类型
      if (!this.$utils.checkFileType(file.name, ['jpg', 'jpeg', 'png', 'pdf'])) {
        uni.showToast({
          title: '只能上传jpg/jpeg/png/pdf格式的文件',
          icon: 'none'
        })
        return
      }
      
      // 检查文件大小
      if (file.size > 5 * 1024 * 1024) {
        uni.showToast({
          title: '文件大小不能超过5MB',
          icon: 'none'
        })
        return
      }
      
      // 设置文件
      this.receiptForm.paymentReceipt = file
      this.paymentReceiptList.push({
        url: file.url,
        status: 'success',
        message: '上传成功',
        name: file.name
      })
    },
    
    // 上传发票
    afterInvoiceRead(event) {
      const { file } = event
      
      // 检查文件类型
      if (!this.$utils.checkFileType(file.name, ['jpg', 'jpeg', 'png', 'pdf'])) {
        uni.showToast({
          title: '只能上传jpg/jpeg/png/pdf格式的文件',
          icon: 'none'
        })
        return
      }
      
      // 检查文件大小
      if (file.size > 5 * 1024 * 1024) {
        uni.showToast({
          title: '文件大小不能超过5MB',
          icon: 'none'
        })
        return
      }
      
      // 设置文件
      this.receiptForm.invoice = file
      this.invoiceList.push({
        url: file.url,
        status: 'success',
        message: '上传成功',
        name: file.name
      })
    },
    
    // 删除支付凭证
    deletePaymentReceipt() {
      this.receiptForm.paymentReceipt = null
      this.paymentReceiptList = []
    },
    
    // 删除发票
    deleteInvoice() {
      this.receiptForm.invoice = null
      this.invoiceList = []
    },
    
    // 提交表单
    submitForm() {
      this.$refs.receiptFormRef.validate(async valid => {
        if (!valid) return
        
        if (!this.receiptForm.paymentReceipt) {
          uni.showToast({
            title: '请上传支付凭证',
            icon: 'none'
          })
          return
        }
        
        if (!this.receiptForm.invoice) {
          uni.showToast({
            title: '请上传发票',
            icon: 'none'
          })
          return
        }
        
        this.loading = true
        
        // 构建表单数据
        const formData = new FormData()
        formData.append('userName', this.receiptForm.userName)
        formData.append('department', this.receiptForm.department)
        formData.append('date', this.receiptForm.date)
        formData.append('reason', this.receiptForm.reason)
        formData.append('amount', this.receiptForm.amount)
        formData.append('paymentReceipt', this.receiptForm.paymentReceipt)
        formData.append('invoice', this.receiptForm.invoice)
        
        try {
          // 模拟API请求
          setTimeout(() => {
            uni.showToast({
              title: '提交成功',
              icon: 'success'
            })
            
            // 跳转到结果页
            uni.navigateTo({
              url: '/pages/receipt/result'
            })
            
            this.loading = false
          }, 1500)
          
          // 实际项目中应该是这样的API调用
          // const result = await this.$http.post('/receipt/upload', formData)
          // if (result.code === 0) {
          //   uni.showToast({
          //     title: '提交成功',
          //     icon: 'success'
          //   })
          //   
          //   // 跳转到结果页，并传递结果ID
          //   uni.navigateTo({
          //     url: `/pages/receipt/result?id=${result.data.id}`
          //   })
          // } else {
          //   uni.showToast({
          //     title: result.message || '提交失败',
          //     icon: 'none'
          //   })
          // }
        } catch (error) {
          uni.showToast({
            title: '提交失败，请重试',
            icon: 'none'
          })
        } finally {
          this.loading = false
        }
      })
    },
    
    // 重置表单
    resetForm() {
      this.$refs.receiptFormRef.resetFields()
      this.receiptForm.paymentReceipt = null
      this.receiptForm.invoice = null
      this.paymentReceiptList = []
      this.invoiceList = []
      this.receiptForm.dateDisplay = ''
      
      // 重新设置用户信息
      this.receiptForm.userName = this.userInfo.name || ''
      this.receiptForm.department = '财务部'
    }
  }
}
</script>

<style lang="scss" scoped>
.receipt-upload-container {
  padding: 30rpx;
  background-color: #ffffff;
  min-height: 100vh;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 50rpx;
  margin-bottom: 30rpx;
  
  .u-button {
    width: 45%;
  }
}
</style> 